<template>
  <div class="app-container">
    <!-- 查询表单 -->
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['preempt:preempt:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['preempt:preempt:edit']"
        >设置活动时间</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['preempt:preempt:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['preempt:preempt:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <!-- 商品抢兑表格 -->
    <el-table v-loading="loading" :data="preemptList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
     
      <el-table-column label="商品ID" align="center" prop="productId" />
      <el-table-column label="商品名" align="center" prop="products.productName" />
      <el-table-column label="原价格" align="center" prop="products.pointsPrice" >
        <template slot-scope="scope">
          <div :style="{ color: scope.row.products.pointsPrice ? 'red' : 'red' }">
            {{ scope.row.products.pointsPrice }}
          </div>
        </template>
      </el-table-column>
      <el-table-column label="活动价格" align="center" prop="price" >
        <template slot-scope="scope">
          <div :style="{ color: scope.row.price ? 'MediumVioletRed' : 'red' }">
            {{ scope.row.price }}
          </div>
        </template>
      </el-table-column>
      <el-table-column label="商品图片链接" align="center" prop="products.image" width="100">
        <template slot-scope="scope">
          <image-preview :src="scope.row.products.image" :width="50" :height="50"/>
        </template>
      </el-table-column>
      <el-table-column label="活动库存" align="center" prop="stock" />
      <el-table-column label="开始时间" align="center" prop="time" />
      <el-table-column label="结束时间" align="center" prop="endtime" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['preempt:preempt:edit']"
          >设置活动时间</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['preempt:preempt:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改商品抢兑对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="商品ID" prop="productId">
          <el-input v-model="form.productId" placeholder="请输入商品ID" />
        </el-form-item>
        <el-form-item label="活动价格" prop="price">
          <el-input v-model="form.price" placeholder="请输入活动价格" />
        </el-form-item>
        <el-form-item label="抢占库存" prop="stock">
          <el-input v-model="form.stock" placeholder="请输入抢占库存，必须大于等于0" />
        </el-form-item>
        <el-form-item label="活动时间" prop="time">
          <el-date-picker
            v-model="timeRange"
            type="datetimerange"
            range-separator="至"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            value-format="yyyy-MM-dd HH:mm:ss"
            @change="onTimeChange"  
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listPreempt, getPreempt, delPreempt, addPreempt, updatePreempt } from "@/api/preempt/preempt";

export default {
  name: "Preempt",
  data() {
    return {
      timeRange: this.getDefaultTimeRange(),
      loading: true,
      ids: [],
      single: true,
      multiple: true,
      showSearch: true,
      total: 0,
      preemptList: [],
      title: "",
      open: false,
      queryParams: {
        pageNum: 1,
        pageSize: 10,
      },
      form: {
        productId: null,
        price: null,
        stock: null,
        time: null,
        endtime: null
      },
      rules: {
        productId: [
          { required: true, message: "商品ID不能为空", trigger: "blur" }
        ],
        price: [
          { required: true, message: "活动价格不能为空", trigger: "blur" }
        ],
        stock: [
          { required: true, message: "抢占库存不能为空", trigger: "blur" }
        ],
        time: [
          { required: true, message: "活动时间不能为空", trigger: "change" }
        ],
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    onTimeChange(val) {
      if (val && val.length === 2) {
        this.form.time = val[0];
        this.form.endtime = val[1];
      } else {
        this.form.time = null;
        this.form.endtime = null;
      }
    },
    getList() {
      this.loading = true;
      listPreempt(this.queryParams).then(response => {
        this.preemptList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    getDefaultTimeRange() {
      const now = new Date();
      const start = new Date(now.getFullYear(), now.getMonth(), now.getDate(), 20, 30, 0); // 当天 20:30
      const end = new Date(now.getFullYear(), now.getMonth(), now.getDate() + 1, 20, 30, 0); // 第二天 20:30
      return [start, end];
    },
    formatDate(date) {
      const pad = (num) => (num < 10 ? '0' + num : num);
      return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())} ${pad(date.getHours())}:${pad(date.getMinutes())}:${pad(date.getSeconds())}`;
    },
    cancel() {
      this.open = false;
      this.reset();
    },
    reset() {
      this.form = {
        productId: null,
        price: null,
        stock: null,
        time: null,
        endtime: null
      };
      this.timeRange = this.getDefaultTimeRange(); // 重置时间范围
      this.resetForm("form");
    },
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加商品抢兑";
    },
    handleUpdate(row) {
      this.reset();
      getPreempt(row.id).then(response => {
        this.form = response.data;
        // 如果返回的时间为空，则使用默认时间范围
        if (!this.form.time || !this.form.endtime) {
          const defaultTimeRange = this.getDefaultTimeRange();
          this.timeRange = defaultTimeRange;
          this.form.time = defaultTimeRange[0];
          this.form.endtime = defaultTimeRange[1];
        } else {
          this.timeRange = [new Date(this.form.time), new Date(this.form.endtime)]; // 设置时间范围
        }
        this.open = true;
        this.title = "修改商品抢兑";
      });
    },
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updatePreempt(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addPreempt(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除商品抢兑编号为"' + ids + '"的数据项？').then(() => {
        return delPreempt(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    handleExport() {
      this.download('preempt/preempt/export', {
        ...this.queryParams
      }, `preempt_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>

<style scoped>
.app-container {
  padding: 20px;
}
.block {
  margin: 20px 0;
}
.demonstration {
  font-weight: bold;
}
</style>
<template>
  <div class="app-container">
    <!-- 查询表单 -->
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['preempt:preempt:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['preempt:preempt:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['preempt:preempt:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['preempt:preempt:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <!-- 商品抢兑表格 -->
    <el-table v-loading="loading" :data="preemptList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="商品ID" align="center" prop="productId" />
      <el-table-column label="商品名" align="center" prop="products.productName" />
      <el-table-column label="原价格" align="center" prop="products.price" >
        <template slot-scope="scope">
          <div :style="{ color: scope.row.products.pointsPrice ? 'red' : 'red' }">
            {{ scope.row.products.pointsPrice }}
          </div>
          </template>
        </el-table-column>
      
      <el-table-column label="活动价格" align="center" prop="price" >
        <template slot-scope="scope">
          <div :style="{ color: scope.row.price ? 'MediumVioletRed' : 'red' }">
            {{ scope.row.price }}
          </div>
        </template>

        </el-table-column>
        <el-table-column label="商品图片链接" align="center" prop="products.image" width="100">
        <template slot-scope="scope">
          <image-preview :src="scope.row.products.image" :width="50" :height="50"/>
        </template>
      </el-table-column>
      <el-table-column label="活动库存" align="center" prop="stock" />
      <el-table-column label="开始时间" align="center" prop="time" />
      <el-table-column label="结束时间" align="center" prop="endtime" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['preempt:preempt:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['preempt:preempt:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改商品抢兑对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="商品ID" prop="productId">
          <el-input v-model="form.productId" placeholder="请输入商品ID" />
        </el-form-item>

        <el-form-item label="活动价格" prop="price">
          <el-input v-model="form.price" placeholder="请输入活动价格" />
        </el-form-item>

        <el-form-item label="抢占库存" prop="stock">
          <el-input v-model="form.stock" placeholder="请输入抢占库存，必须大于等于0" />
        </el-form-item>

        <el-form-item label="活动时间" prop="time">
          <el-date-picker
            v-model="timeRange"
            type="datetimerange"
            range-separator="至"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            value-format="yyyy-MM-dd HH:mm:ss"
            @change="onTimeChange"  
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listPreempt, getPreempt, delPreempt, addPreempt, updatePreempt } from "@/api/preempt/preempt";

export default {
  name: "Preempt",
  data() {
    return {
      timeRange: this.getDefaultTimeRange(),
      timeRange: [], // 用于存储活动的开始和结束时间
      loading: true,
      ids: [],
      single: true,
      multiple: true,
      showSearch: true,
      total: 0,
      preemptList: [],
      title: "",
      open: false,
      queryParams: {
        pageNum: 1,
        pageSize: 10,
      },
      form: {},
      rules: {
        productId: [
          { required: true, message: "商品ID不能为空", trigger: "blur" }
        ],
        price: [
          { required: true, message: "活动价格不能为空", trigger: "blur" }
        ],
        stock: [
          { required: true, message: "抢占库存不能为空", trigger: "blur" }
        ],
        time: [
          { required: true, message: "活动时间不能为空", trigger: "change" }
        ],
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    onTimeChange(val) {
        if (val && val.length === 2) {
            const start = new Date(val[0]);
            start.setHours(20, 30, 0);
            const end = new Date(val[1]);
            end.setHours(20, 30, 0);

            this.timeRange = [start, end];
            this.form.time = this.formatDate(start);
            this.form.endtime = this.formatDate(end);
        } else {
            this.form.time = null;
            this.form.endtime = null;
        }
    },
    getList() {
      this.loading = true;
      listPreempt(this.queryParams).then(response => {
        this.preemptList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    getDefaultTimeRange() {
      const now = new Date();
      const start = new Date(now.getFullYear(), now.getMonth(), now.getDate(), 20, 30, 0); // 当天 20:30
      const end = new Date(now.getFullYear(), now.getMonth(), now.getDate() + 1, 20, 30, 0); // 第二天 20:30
      return [start, end];
    },
    formatDate(date) {
        const pad = (num) => (num < 10 ? '0' + num : num);
        return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())} ${pad(date.getHours())}:${pad(date.getMinutes())}:${pad(date.getSeconds())}`;
    },
    cancel() {
      this.open = false;
      this.reset();
    },
    reset() {
      this.form = {
        productId: null,
        price: null,
        stock: null,
        time: null,
        endtime: null
      };
      this.timeRange = this.getDefaultTimeRange(); // 重置时间范围
      this.resetForm("form");
    },
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加商品抢兑";
    },
     // 打开修改对话框
     handleUpdate(row) {
  this.reset();
  getPreempt(row.id).then(response => {
    this.form = response.data;
    // 如果返回的时间为空，则使用默认时间范围
    if (!this.form.time || !this.form.endtime) {
      const defaultTimeRange = this.getDefaultTimeRange();
      this.timeRange = defaultTimeRange;
      this.form.time = this.formatDate(defaultTimeRange[0]);
      this.form.endtime = this.formatDate(defaultTimeRange[1]);
    } else {
      const start = new Date(response.data.time);
      const end = new Date(response.data.endtime);
      this.timeRange = [start, end]; // 设置时间范围
    }
    this.open = true;
    this.title = "修改商品抢兑";
  });
},

    // 监听时间变化方法
  
    submitForm() {
        this.$refs["form"].validate(valid => {
            if (valid) {
                if (this.form.id != null) {
                    updatePreempt(this.form).then(response => {
                        this.$modal.msgSuccess("修改成功");
                        this.open = false;
                        this.getList();
                    });
                } else {
                    addPreempt(this.form).then(response => {
                        this.$modal.msgSuccess("新增成功");
                        this.open = false;
                        this.getList();
                    });
                }
            }
        });
    },

    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除商品抢兑编号为"' + ids + '"的数据项？').then(() => {
        return delPreempt(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    handleExport() {
      this.download('preempt/preempt/export', {
        ...this.queryParams
      }, `preempt_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>

<style scoped>
.app-container {
    padding: 20px;
}
.block {
    margin: 20px 0;
}
.demonstration {
    font-weight: bold;
}
</style>
